<template>
  <div class="box">
    请输入内容：
    <p>
      <el-input v-model="value" />
      <el-button type="primary" @click="submit('bar')">生成一维码</el-button>
      <el-button type="primary" @click="submit('qr')">生成二维码</el-button>
      <el-button type="danger" @click="clearCode('qr')">全部清空</el-button>
      <el-button type="danger" @click="link()">网易云测试</el-button>
    </p>
    <p>
      <a href="cloudmusic://">打开网易云音乐</a>
    </p>
    <a href="weixin://">打开wx</a>
    <barcode :value="barCodeValue" v-bind="barOption"></barcode>
    <div ref="qrCodeUrl"></div>

    <div>{{ formatSizeUnits(units) }}</div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2"; // 引入qrcodejs2 二维码
import VueBarcode from 'vue-barcode'; // 引入vue-barcode 一维码
export default {
  name: 'BarQrCodeView',
  components: {
    'barcode': VueBarcode
  },
  data() {
    return {
      value: '',
      qrcode: '',
      barCodeValue: '',
      barOption: {
        width: 2,
        height: 50,
        background: '#f00'
      },
      units: '12312312311144441'
    }
  },
  methods: {
    submit(type) {
      if (type === 'bar') {
        this.barCodeValue = this.value
      } else if (type === 'qr') {
        // 创建前先清空
        this.$refs.qrCodeUrl.innerHTML = ''
        // this.qrcode.makeCode("http://naver.com");
        this.qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text: this.value, // 需要转换为二维码的内容
          width: 100,
          height: 100,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        })
      }
    },
    clearCode() {
      this.$refs.qrCodeUrl.innerHTML = ''
      this.barCodeValue = ''
    },
    formatSizeUnits(kb) {
      let units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      let unitIndex = 0;
      while (kb >= 1024 && unitIndex < units.length - 1) {
        kb /= 1024;
        unitIndex++;
      }
      return `${kb.toFixed(2)} ${units[unitIndex]}`
    },
    link() {
      window.open('wyy://123')
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  width: 500px;
  margin: 0 auto;
  padding: 20px;
  text-align: left;

  .editor-box {
    border: 1px solid #ddd;
    min-height: 40px;
    border-radius: 5px;

    &:focus-visible {
      border: 1px solid #f00;
      outline: none;
    }
  }
}
</style>
